<script setup lang="ts">
import { onMounted, ref } from "vue";
import {
  getProduceWorkOrderApi,
  putProduceWorkOrderUpdateApi,
} from "@/api/Produce";
import {
  ProductionWorkOrderListData,
  ProductionWorkOrderData,
} from "@/api/Produce/res";
import { ProduceOrderSearchType, PaginationType } from "@/api/Produce/params";
import { ElMessage, rowProps } from "element-plus";
import { useRouter } from "vue-router";

// 枚举操作
enum operate {
  START = "开始",
  CANCEL = "取消",
  END = "结束",
  REVOKE = "撤回",
}

enum orderStatus {
  DOING = "进行中",
  NOT_START = "未开始",
  CLOSED = "已关闭",
  FINISH = "已完成",
  PAUSE = "已暂停",
}

// mockData
let sourceData = ref(["销售订单", "库存备货", "其他"]);
let stateData = ref(["进行中", "未开始", "已完成", "已关闭", "已暂停"]);
let params = ref<PaginationType>({
  currentPage: 1,
  pageSize: 10,
});
let ifSearch = ref(false);
let tableData = ref([{}]);
let total = ref(0);
let showDatePicker = ref(false);
let selectedData = ref<ProductionWorkOrderData[]>([]);
let orderSearchData = ref<ProduceOrderSearchType>({
  workOrderName: "",
  relatedPlan: "",
  productName: "",
  status: "",
  requiredDate: "",
  plannedStartTime: "",
  plannedEndTime: "",
  actualStartTime: "",
  actualEndTime: "",
});
const $router = useRouter();
const filteredSearchData: Partial<ProduceOrderSearchType> = {};
let loading = ref(false);

const handler = (page) => {
  params.value.currentPage = page;
  if (ifSearch.value) {
    getTableData(filteredSearchData);
  } else {
    getTableData();
  }
};
const sizeHandler = (page_size) => {
  params.value.pageSize = page_size;
  if (ifSearch.value) {
    getTableData(filteredSearchData);
  } else {
    getTableData();
  }
};
const gotoDetail = (objectId, status) => {
  $router.push({
    path: "/production/orderDetail",
    query: { objectId, status },
  });
};
const onSearch = () => {
  let allFieldsEmpty = true;
  Object.keys(filteredSearchData).forEach((key) => {
    delete filteredSearchData[key];
  });
  for (const key in orderSearchData.value) {
    if (orderSearchData.value[key] !== "") {
      allFieldsEmpty = false;
      filteredSearchData[key] = orderSearchData.value[key];
    }
  }
  ifSearch.value = !allFieldsEmpty;
  params.value.currentPage = 1;
  params.value.pageSize = 10;
  getTableData(filteredSearchData);
};
const reset = () => {
  orderSearchData.value = {
    workOrderName: "",
    relatedPlan: "",
    productName: "",
    status: "",
    requiredDate: "",
    plannedStartTime: "",
    plannedEndTime: "",
    actualStartTime: "",
    actualEndTime: "",
  };
  params.value.currentPage = 1;
  params.value.pageSize = 10;
  ifSearch.value = false;
  getTableData();
};
const onSelect = (selection: ProductionWorkOrderData[]) => {
  selectedData.value = selection;
};
const operateOrder = async (operate) => {
  if (selectedData.value.length != 0) {
    let status = "";
    let progress = 0;
    switch (operate) {
      case "开始":
        status = orderStatus.DOING;
        break;
      case "取消":
        status = orderStatus.CLOSED;
        break;
      case "结束":
        status = orderStatus.FINISH;
        break;
      case "撤回":
        status = orderStatus.PAUSE;
        break;
      default:
        status = "";
    }
    try {
      const updates = selectedData.value.map((item) => {
        return putProduceWorkOrderUpdateApi({
          objectId: item.objectId,
          status,
          progress:
            status == "已完成"
              ? "100"
              : status == "已关闭"
              ? "0"
              : item.progress,
        });
      });

      await Promise.all(updates);
      ElMessage({ type: "success", message: "批量操作成功" });
      getTableData();
    } catch (err: any) {
      ElMessage({ type: "error", message: err.message });
    }
  } else {
    ElMessage({ type: "warning", message: "请先选择工单任务" });
  }
};

const getTableData = async (data?) => {
  try {
    loading.value = true;
    const TotalRes = await getProduceWorkOrderApi();
    total.value = TotalRes.results.length;
    const res: ProductionWorkOrderListData = await getProduceWorkOrderApi(
      data,
      params.value
    );
    tableData.value = res.results;
    if (ifSearch.value) {
      total.value = res.results.length;
    }
  } catch (err: any) {
    ElMessage({ type: "error", message: err.message });
  } finally {
    loading.value = false;
  }
};

const gotoTask = (objectId, status, progress) => {
  $router.push({
    path: "/production/taskDetail",
    query: {
      objectId,
      status,
      progress,
    },
  });
};

onMounted(() => {
  getTableData();
});
</script>

<template>
  <div style="padding: 20px">
    <el-card>
      <div class="operateContainer">
        <div
          class="formContainer"
          :style="showDatePicker ? 'height:138px' : 'height:32px'"
        >
          <el-form inline :model="orderSearchData">
            <el-form-item prop="workOrderName">
              <el-input
                placeholder="请输入任务编号/名称"
                style="width: 250px"
                v-model.trim="orderSearchData.workOrderName"
              ></el-input>
            </el-form-item>
            <el-form-item prop="relatedPlan">
              <el-input
                placeholder="请输入计划编号/名称"
                style="width: 250px"
                v-model.trim="orderSearchData.relatedPlan"
              ></el-input>
            </el-form-item>
            <el-form-item prop="productName">
              <el-input
                placeholder="请输入产品名称"
                style="width: 250px"
                v-model.trim="orderSearchData.productName"
              ></el-input>
            </el-form-item>
            <el-form-item prop="status">
              <el-select
                placeholder="请选择状态"
                style="width: 180px"
                v-model.trim="orderSearchData.status"
              >
                <el-option
                  v-for="item in stateData"
                  :key="item"
                  :label="item"
                  :value="item"
                ></el-option>
              </el-select>
            </el-form-item>
            <div style="margin-top: 20px">
              <el-form-item prop="plannedStartTime">
                <el-date-picker
                  style="width: 250px"
                  type="date"
                  placeholder="请选择计划开始时间"
                  v-model.trim="orderSearchData.plannedStartTime"
                ></el-date-picker>
              </el-form-item>
              <el-form-item prop="plannedEndTime">
                <el-date-picker
                  style="width: 250px"
                  type="date"
                  placeholder="请选择计划结束时间"
                  v-model.trim="orderSearchData.plannedEndTime"
                ></el-date-picker>
              </el-form-item>
              <el-form-item prop="actualStartTime">
                <el-date-picker
                  style="width: 250px"
                  type="date"
                  placeholder="请选择实际开始时间"
                  v-model.trim="orderSearchData.actualStartTime"
                ></el-date-picker>
              </el-form-item>
            </div>
            <div style="margin-top: 20px">
              <el-form-item prop="actualEndTime">
                <el-date-picker
                  style="width: 250px"
                  type="date"
                  placeholder="请选择实际结束时间"
                  v-model.trim="orderSearchData.actualEndTime"
                ></el-date-picker>
              </el-form-item>
              <el-form-item prop="requiredDate">
                <el-date-picker
                  style="width: 250px"
                  type="date"
                  placeholder="请选择需求日期"
                  v-model.trim="orderSearchData.requiredDate"
                ></el-date-picker>
              </el-form-item>
            </div>
          </el-form>
        </div>
        <div class="searchOperate">
          <div class="button">
            <el-button type="primary" plain style="width: 80px" @click="reset"
              >重置</el-button
            >
            <el-button type="primary" style="width: 80px" @click="onSearch"
              >查询</el-button
            >
          </div>
          <div class="more">
            <el-button
              type="primary"
              link
              @click="showDatePicker = !showDatePicker"
              >更多
            </el-button>
            <el-icon color="#1B9AEE" :class="{ 'rotate-180': showDatePicker }">
              <CaretBottom />
            </el-icon>
          </div>
        </div>
      </div>
    </el-card>
    <el-card style="margin-top: 20px">
      <template #header>
        <span style="font-weight: bold">生产工单</span>
      </template>
      <div class="oprate">
        <el-button
          style="width: 80px"
          type="primary"
          plain
          @click="operateOrder(operate.START)"
          >开始</el-button
        >
        <el-button
          style="width: 80px"
          type="primary"
          plain
          @click="operateOrder(operate.CANCEL)"
          >取消</el-button
        >
        <el-button
          style="width: 80px"
          type="primary"
          plain
          @click="operateOrder(operate.END)"
          >完成</el-button
        >
        <el-button
          style="width: 80px"
          type="primary"
          plain
          @click="operateOrder(operate.REVOKE)"
          >撤回</el-button
        >
      </div>
      <el-table
        :data="tableData"
        style="margin-top: 15px"
        border
        @select="onSelect"
        @select-all="onSelect"
        v-loading="loading"
      >
        <el-table-column type="selection" align="center"> </el-table-column>
        <el-table-column
          align="center"
          label="序号"
          type="index"
          width="60"
          fixed="left"
        ></el-table-column>
        <el-table-column
          align="center"
          label="工单编号"
          fixed="left"
          width="100"
          prop="workOrderNumber"
        ></el-table-column>

        <el-table-column
          align="center"
          label="工单名称"
          fixed="left"
          width="100"
          prop="workOrderName"
        ></el-table-column>

        <el-table-column
          align="center"
          label="工单进度"
          fixed="left"
          width="200"
          prop="progress"
        >
          <template #="{ row, $index }">
            <el-progress
              :text-inside="true"
              :stroke-width="26"
              :percentage="row.progress"
              :color="
                row.status == orderStatus.CLOSED
                  ? '#909399'
                  : row.status == orderStatus.PAUSE
                  ? '#ADD8F7'
                  : ''
              "
              :status="row.status == orderStatus.FINISH ? 'success' : ''"
            ></el-progress>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="关联计划"
          width="110"
          prop="relatedPlan"
        ></el-table-column>

        <el-table-column
          align="center"
          label="产品名称"
          width="90"
          prop="productName"
        ></el-table-column>

        <el-table-column
          align="center"
          label="产品编号"
          width="90"
          prop="productNumber"
        ></el-table-column>

        <el-table-column
          align="center"
          label="规格型号"
          width="90"
          prop="specificationModel"
        ></el-table-column>

        <el-table-column
          align="center"
          label="产品类型"
          width="90"
          prop="productType"
        ></el-table-column>

        <el-table-column
          align="center"
          label="单位"
          width="90"
          prop="unit"
        ></el-table-column>

        <el-table-column
          align="center"
          label="需求日期"
          width="100"
          prop="requiredDate"
        ></el-table-column>

        <el-table-column
          align="center"
          label="计划数量"
          width="90"
          prop="plannedQuantity"
        ></el-table-column>

        <el-table-column
          align="center"
          label="实际生产数量"
          width="110"
          prop="actualQuantity"
        ></el-table-column>

        <el-table-column
          align="center"
          label="计划开工时间"
          width="140"
          prop="plannedStartTime"
        ></el-table-column>

        <el-table-column
          align="center"
          label="计划完工时间"
          width="140"
          prop="plannedEndTime"
        ></el-table-column>

        <el-table-column
          align="center"
          label="实际开工时间"
          width="140"
          prop="actualStartTime"
        ></el-table-column>

        <el-table-column
          align="center"
          label="实际完工时间"
          width="140"
          prop="actualEndTime"
        ></el-table-column>

        <el-table-column
          align="center"
          label="状态"
          prop="status"
        ></el-table-column>
        <el-table-column align="center" label="操作" fixed="right" width="200">
          <template #="{ row, $index }">
            <!-- <el-button link type="primary" @click="handleClick">
              排产
            </el-button> -->
            <el-button
              link
              type="primary"
              :disabled="row.status !== '进行中'"
              @click="gotoTask(row.objectId, row.status, row.progress)"
            >
              工序
            </el-button>
            <el-button
              link
              type="primary"
              @click="gotoDetail(row.objectId, row.status)"
              >查看</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-model:current-page="params.currentPage"
        v-model:page-size="params.pageSize"
        :page-sizes="[10, 20, 30, 40]"
        :background="true"
        layout="prev,pager,next,jumper,->,sizes,total"
        :total="total"
        @current-change="handler"
        @size-change="sizeHandler"
        style="margin-top: 10px"
      ></el-pagination>
    </el-card>
  </div>
</template>

<style scoped lang="scss">
.operateContainer {
  display: flex;
  align-content: center;
  justify-content: space-between;

  .formContainer {
    width: 1060px;
    height: 32px;
    transition: height 0.3s ease; // 添加高度变化的过渡效果
    overflow: hidden; // 防止内容溢出
    .el-form-item {
      margin-bottom: 0;
    }
  }

  .searchOperate {
    display: flex;
    align-items: center;

    .more {
      margin-left: 20px;
      display: flex;
      align-items: center;
    }
  }
}

/* 定义旋转动画 */
.rotate-180 {
  transition: transform 0.3s ease;
  transform: rotate(180deg);
}
</style>
